package com.hainatong.shiphelper.module.warehouse.fragment;


import android.os.Bundle;
import android.view.View;
import cn.bertsir.zbar.Qr.ScanResult;
import cn.bertsir.zbar.QrManager;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hainatong.shiphelper.*;
import com.hainatong.shiphelper.databinding.FragmentRukuAddListBinding;
import com.hainatong.shiphelper.mainhome.ComFragmentActivity;
import com.hainatong.shiphelper.mainhome.fragment.CommonResultFragment;
import com.hainatong.shiphelper.module.warehouse.adapter.ItemChukuAdapter;
import com.hainatong.shiphelper.module.warehouse.entity.ChuKuRaramBean;
import com.hainatong.shiphelper.module.warehouse.entity.ChukuGoodsParam;
import com.hainatong.shiphelper.module.warehouse.viewmodel.ReturnViewModel;
import com.hainatong.shiphelper.utils.RecyclerViewHelper;
import com.hainatong.shiphelper.widget.LoadingDialog;
import com.hainatong.mvvmbase.rxbus.RxBusBaseMessage;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.xui.XUI;
import com.xuexiang.xui.widget.dialog.DialogLoader;


public class ReturnAddFragment extends MvvmLazyFragment<FragmentRukuAddListBinding, ReturnViewModel>
{
    private static String RETURN_ADD_TAG = "ReturnAddFragment";

    private String goodsCode ;

    private ItemChukuAdapter adapter;

    private LoadingDialog loading;

    public static ReturnAddFragment newInstance(String scanCode)
    {
        Bundle bundle = new Bundle();
        bundle.putString( RETURN_ADD_TAG , scanCode );
        ReturnAddFragment returnFragment = new ReturnAddFragment();
        returnFragment.setArguments( bundle );
        return returnFragment;
    }

    @Override
    public int getLayoutId()
    {
        return R.layout.fragment_ruku_add_list;
    }

    @Override
    public int getBindingVariable()
    {
        return 0;
    }

    @Override
    protected void initParameters()
    {
        Bundle args = getArguments();
        if(  args != null )
        {
            goodsCode = args.getString(RETURN_ADD_TAG , "");
        }
        XUI.initTheme(getActivity());
    }

    @Override
    protected void onRetryBtnClick()
    {}

    @Override
    protected void initView(View view)
    {
        loading = new LoadingDialog( getActivity(), getString( R.string.loading ) );
        adapter = new ItemChukuAdapter();
        adapter.setShowMore(true);
        RecyclerViewHelper.addLinerLayoutMgrNoDecoration( viewDataBinding.recyclerview );
        viewDataBinding.recyclerview.setAdapter( adapter );

        adapter.addChildClickViewIds(R.id.btn_more);
        adapter.setOnItemChildClickListener((adapter1, view1, position) -> {
            ChukuGoodsParam tempGoods = adapter.getItem(position);
            if( view1.getId() == R.id.btn_more )
            {
                //显示弹出框
                DialogLoader.getInstance()
                            .showContextMenuDialog(getActivity(),"申请",new String[]{"报废申请","删除"},(dialog, which) -> {

                          if( which == 0 )
                          {
                              // 跳转 破损提交
                              ComFragmentActivity.startViewByParam( getActivity(),Constants.VIEW_TYPE_BROKEN_SUB,tempGoods.getImpa_code() );
                          }
                          else if(which ==1)
                          {
                              adapter.removeAt(position);
                              setTotalSize( adapter.getData().size() );
                          }
                });
            }
        });

        viewDataBinding.fabAdd.setOnClickListener( v -> {
            //扫描 归还商品
            startScanQrcode();

        } );

        viewDataBinding.tvOk.setOnClickListener( v -> {
            //点击 完成
            //提交 归还 物资
            if( !adapter.getData().isEmpty() )
            {
                String chargeUser = GlobalConfig.getInstance().getUserInfo().getUserTrueName();
                String chargeUserId = GlobalConfig.getInstance().getUserInfo().getUuid();

                ChuKuRaramBean[] returnBeans = ReturnViewModel.getReturnParams( adapter.getData(),chargeUser,chargeUserId);
                loading.show();
                viewModel.returnTask(returnBeans);
            }

        } );


        LiveEventBus.get( ReturnTaskFragment.FINISH_ADD_RETURN_GOODS, ChukuGoodsParam.class )
                .observe( this , goodsParam ->{
                    //添加 选择的 物资 信息
                    adapter.addData( goodsParam );
                    adapter.notifyDataSetChanged();
                    setTotalSize( adapter.getData().size() );

                } );

    }

    @Override
    protected void lazyLoad()
    {
        viewModel.getReturnResult().observe(this,result -> {
            loading.hide();
            if( result.isSuccess() )
            {
                RxBusBaseMessage rxMsg = new RxBusBaseMessage(CommonResultFragment.RETURN_SUCCESS_RESULT , result.getData() );
                // 切换 显示 出库 成功页面
                ((ComFragmentActivity)getActivity()).showCommonResult( rxMsg );

            }
            else
            {
                ToastUtils.showShort( result.getMsg() );
            }
        });
    }

    private void setTotalSize(int size)
    {
        String totalCount = String.format( getString( R.string.has_ruku_count ), String.valueOf( size ) );
        viewDataBinding.tvSelectTotal.setText( totalCount );
    }

    public void startScanQrcode( )
    {
        QrManager.getInstance().init( App.getScanQrConfigByType( 4 ) ).startScan(getActivity(), new QrManager.OnScanResultCallback() {
            @Override
            public void onScanSuccess(ScanResult result)
            {
                LogUtils.e(TAG, "onScanSuccess: " + result.getContent());
                if( result.getType() == ScanResult.CODE_QR)
                {
                    //扫描 获取商品 条码  code
                    //ToastUtils.showShort( result.getContent() );
                    // 跳转 归还任务
                    ComFragmentActivity.startViewByParam( getActivity(),Constants.VIEW_TYPE_RETURN_TASK, result.getContent());
                }
                else
                {
                    ToastUtils.showShort( result.getContent() );
                }
            }
        });
    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        loading.dismiss();
    }
}
